package cn.ys.pet.service.impl;

import cn.ys.pet.domain.PetType;
import cn.ys.pet.mapper.PetTypeMapper;
import cn.ys.pet.service.IPetTypeService;
import cn.ys.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ys
 * @since 2023-01-08
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    // 无限极树上下级
    @Override
    public List<PetType> tree() {
        ArrayList list = new ArrayList<>();
        // 查询全部
        List<PetType> typeList = petTypeMapper.findAll();
        Map<Long, PetType> typeMap = typeList.stream().collect(Collectors.toMap(PetType::getId, type -> type));
        typeList.forEach(type -> {
            if(type.getPid() == null){
                list.add(type);
            }else {
                PetType petType = typeMap.get(type.getId());
                petType.getChildren().add(type);
            }
        });
        return list;
    }
}
